import axios from "axios";
const service = axios.create({
  baseURL: process.env.BASE_URL,
  responseType: 'arraybuffer',
})

service.interceptors.request.use(config => {
  config.headers['Authorization'] = window.sessionStorage.getItem('token');
  return config;
}, error => {
  console.log(error);
})

service.interceptors.response.use(res =>{
  const headers = res.headers;
  let reg = RegExp(/application\/json/)
  if (headers['content-type'].match(reg)){
   res.data = unitToString(res.data); // 转化为JSON字符串对象
  }else{
    let fileDownload = require('js-file-download');
    // let fileName = headers['content-disposition'].split(';')[1].split('filename=')[1];
    // 上方代码找不到 直接写死
    let fileName = "员工表.xlsx"
    let contentType = headers['content-type'];
    fileName = decodeURIComponent(fileName);
    fileDownload(res.data, fileName, contentType);
  }
}, error => {
  console.log(error);
})

function unitToString(unitArray){
  let encodeString = String.fromCharCode.apply(null, new Uint8Array(unitArray));
  let decodeString = decodeURIComponent(escape(encodeString))
  return JSON.parse(decodeString);
}

const baseURL = process.env.BASE_URL;
export {service, baseURL}
